import * as React from 'react';
import { Button, Input, Select, Modal, message } from 'antd';
import MdEditor from 'react-markdown-editor-lite'
import 'react-markdown-editor-lite/lib/index.css';
import PubSub from 'pubsub-js';
import MarkdownIt from 'markdown-it'
import './AddArticle.less'
import ArticleComplete from '../../components/ArticleComplete/ArticleComplete';
import { reqAddArticle, reqCategorys, reqUpdateArticle } from '../../axios';
import { category } from '../CategoryList/CategoryList';
import { RouteComponentProps } from 'react-router-dom';

export interface AddArticleProps extends RouteComponentProps{

}

export interface AddArticleState {
    articleTitle: string,
    articleContent: string,
    articleCateoryId: any,
    articleCompleteShow: boolean
    categorys: category[]
    isAdd:Boolean
}
export interface article {
    content: string,
    cover: string,
    isOriginal: number,
    isTop: number,
    summary: string,
    title: string,
    categoryId: number,
    oppose: number,
    read:number,
    support:number,
    id:number
}

class AddArticle extends React.Component<AddArticleProps, AddArticleState> {
    articleObj={}
    imgUrl: string = ''
    brief: string = ''
    tags: string[] = []
    isTop: number = 0
    isOriginal: number = 0
    constructor(props: AddArticleProps) {
        super(props)
        this.state = {
            isAdd: true,
            articleTitle: '',
            articleContent: '',
            articleCateoryId: 0,
            articleCompleteShow: false,
            categorys: [{
                id: 0,
                icon: '',
                name: '',
                orderNum: 0
            }]
        }
    }

    async componentDidMount() {
        //初始化分类下拉框
        const response = await reqCategorys({});
        if (response.data.success) {
            this.setState({ categorys: response.data.data.records, articleCateoryId: response.data.data.records[0].id })
        }
        //发布订阅获取子组件的属性
        PubSub.subscribe('imgUrlAndBrief', this.getImgAndBrief);
        PubSub.subscribe('tags', this.getTags);
        //接收回显数据
        //@ts-ignore
        const {articleObj} = this.props.location.state||{};
        if(articleObj){
          console.log(articleObj);
          
            const {article} = articleObj;
            this.articleObj = articleObj;
            
            this.setState({
                isAdd:false,
                articleContent:article.content,
                articleTitle:article.title,
                articleCateoryId:article.categoryId
            });                        
        }
        
    }
    //动态绑定markdown编辑器
    handleEditorChange = ({ html, text }: { html: any, text: any }) => {
        this.setState({ articleContent: text });
    }

    //点击弹出model
    showComplete = () => {
        this.setState({ articleCompleteShow: true })
    }
    //model确认
    handleOk = async () => {
        const { articleTitle, articleContent, articleCateoryId } = this.state;
        const article:article = {
            content: articleContent,
            cover: this.imgUrl,
            isOriginal: this.isOriginal,
            isTop: this.isTop,
            summary: this.brief,
            title: articleTitle,
            categoryId: articleCateoryId,
            oppose: 0,
            read:0,
            support:0,
            id:0
        }
        if(this.state.isAdd){
            const tags = this.tags.map(tag => {
                return {
                    content: tag
                }
            })
            const response = await reqAddArticle({ article, tags });
            if(response.data.success){
                message.success(response.data.message);
                this.setState({ articleCompleteShow: false });
                this.props.history.push('/main/article/list');
            }
        }else{
            //@ts-ignore
            const id=this.articleObj.article.id;  
            //@ts-ignore
            article.oppose = this.articleObj.article.oppose;
            //@ts-ignore
            article.read = this.articleObj.article.read;
            //@ts-ignore
            article.support = this.articleObj.article.support;
            //@ts-ignore  
            article.id=id;       
            const tags = this.tags.map((tag) => {
                return {
                    articleId:id,
                    content: tag,
                }
            })
            const response = await reqUpdateArticle({article, tags});            
            if(response.data.success){
                message.success(response.data.message);
                this.setState({ articleCompleteShow: false });
                this.props.history.push('/main/article/list');
            }else{
              message.error(response.data.message);
            }
        }
    };
    //model取消
    handleCancel = () => {
        this.setState({ articleCompleteShow: false })
    };
    //订阅回调 获取子类输入的图片和简介
    getImgAndBrief = (msg: any, obj: any) => {
        const { imageUrl, brief, isTop, isOriginal } = obj
        this.imgUrl = imageUrl;
        this.brief = brief;
        this.isTop = isTop;
        this.isOriginal = isOriginal;
    }
    //订阅回调 获取标签
    getTags = (msg: any, tags: string[]) => {
        this.tags = tags
    }
    render() {
        const mdParser = new MarkdownIt();
        const { articleContent, articleCompleteShow, categorys, articleCateoryId,articleTitle } = this.state;
        return (
            <div>
                <Modal destroyOnClose title="完善文章信息" visible={articleCompleteShow} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <ArticleComplete articleObj={this.articleObj}></ArticleComplete>
                </Modal>

                <div>
                    <Input placeholder='文章标题' value={articleTitle} className='input-title' onChange={(e) => this.setState({ articleTitle: e.target.value })}></Input>
                    <Select value={articleCateoryId} onChange={(value) => this.setState({ articleCateoryId: value })}>
                        {
                            categorys.map((category: category) => {
                                return (
                                    <Select.Option key={category.id} value={category.id}>{category.name}</Select.Option>
                                )
                            })
                        }
                    </Select>
                    <Button onClick={this.showComplete} type='primary' className='article-add-btn'>添加按钮</Button>
                </div>
                <MdEditor
                    placeholder='文章内容'
                    value={articleContent}
                    style={{ height: "500px" }}
                    renderHTML={(text) => mdParser.render(text)}
                    onChange={this.handleEditorChange}
                />
            </div>
        )
    }


}

export default AddArticle;